import 'package:dio/dio.dart';
import 'package:fsharing/core/models/account_detail.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class AccountDetailModel extends ViewModel {
  final Api api;
  final int id;

  final List<AccountDetail> _list = [];
  String _errorMessage;
  List<AccountDetail> _pageList;

  AccountDetailModel(this.api, this.id) : super() {
    _initData();
  }

  List<AccountDetail> get list => _list;

  String get errorMessage => _errorMessage;

  List<AccountDetail> get pageList => _pageList;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      // 获取数据
      _pageList = await api.accountDetail(id, 0);
      _list.addAll(_pageList);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      _pageList = await api.accountDetail(id, _list.length ~/ 10);
      _list.addAll(_pageList);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
